import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {CudTableService} from '../../../public/serve/cud-table/cud-table.service';
import {Service} from '../../../server/server';
import { RemoveTableService } from '../../../public/serve/remove-table/remove-table.service';
import {HintsService} from '../../../public/serve/hints/hints.service';
import { keywordTableAddtype } from '../keywordtable.data';
import { BaseTreeComponent } from '../../../public/components/base-tree/base-tree.component';
import { TreeNode } from '../../../public/common/api';


declare var $:any;

@Component({
  selector: 'app-keyword-table-table',
  templateUrl: './keyword-table-table.component.html',
  styleUrls: ['./keyword-table-table.component.css']
})

export class KeywordTableTableComponent implements OnInit {

    loading: boolean;
    pageSize      : number = 20;
    total      : number = 0;
    naturalNum : number = 0;
    startTime : String = '';
    endTime : String = '';
    details    : object;
    isSelectAll : boolean = false;
    isChose     : boolean = false;

    public isSelect: boolean = true;
    public isDisable: any;              // 按钮（启用/禁用）
    totalRecords: number;
    public totalItems: number;

    public tabVal: any;
    public rolesData: any[];

    queryData : any;

    public files: TreeNode[];
    right: any = {
        "systemTable": {},
    };

    constructor( public removeTableService: RemoveTableService,private http: HttpClient, private hintsService: HintsService, private server: Service, private router: Router, private tableListService: CudTableService) {
        this.right = $.extend(this.right, server.getRight());
    }

    @Input() searchData: any;
    @Input() tableNumber: number;
    public opensearch: boolean;

    ngOnInit() {
        this.loading = true;
        this.themeTableSeventEmit = this.server.themeTableSeventEmit.subscribe((value: any) => {
            this.opensearch = value;
        });
    }

    //取消订阅
    public themeTableSeventEmit: any;
    ngOnDestroy() {
        if (this.themeTableSeventEmit) {
        this.themeTableSeventEmit.unsubscribe();
        }
    }

    @Output()
    tabeListOutput: EventEmitter<string> = new EventEmitter();

    @Output()
    detailsOutput: EventEmitter<keywordTableAddtype> = new EventEmitter();

    // 表格
    public getTabList(queryCriteria) {
        this.loading = true;
        this.queryData = queryCriteria;
        let url = this.server.baseUrl + 'Service/ThemeWords/getThemeTablesList';
        let data = queryCriteria;
        this.tableListService.postRequest(url, data).then((data: any) => {
            this.loading = false;
            if(data.result_code == '0000') {
                this.tabVal = data.result;
                this.files = this._processTreeData(this.tabVal,'themeTableId','parentid','name');
                this.totalRecords = data.length;
                this.tabeListOutput.emit(data.length);
                this.totalItems = data.length;
            }else {
                this.hintsService.messages(data.message, data.result_code);
            }

        }).catch();
    }

    public getChildrenList(queryCriteria,node){
        // this.loading = true;
        let url = this.server.baseUrl + 'Service/ThemeWords/getThemeTablesList';
        let data = queryCriteria;
        this.tableListService.postRequest(url, data).then((data: any) => {
            // this.loading = false;
            if(data.result_code == '0000') {

                node['children'] = this._toTree(data.result, node['themeTableId'], 'themeTableId','parentid','name');
                this.files = [...this.files]
                return false;
                // this.files.forEach((item,index)=>{
                //     if(item['themeTableId'] === node['themeTableId']){
                //         this.files[index] = node;
                //         // this.files = [...this.files]
                //         return false;
                //     }
                // });
            }else {
                this.hintsService.messages(data.message, data.result_code);
            }

        }).catch();
    }

    _processTreeData(list: Array<any>, idName, parentIdName, labelName): Array<any> {
        return this._toTree(list, '0', idName,parentIdName,labelName);
    }

    _toTree(list: Array<any>, topId = '0', idName, parentIdName, labelName) {
        let idKey = idName;
        let result = [];

        for (let item of list) {

            if (item[parentIdName] == topId) {

                let children = {};
                let expandedIcon = 'fa fa-folder-open';
                let collapsedIcon = 'fa fa-folder';
                let leaf = false;

                if(item['child'] == '0'){
                    expandedIcon = '';
                    collapsedIcon = '';
                    leaf = true;
                }

                let dataArr = {
                    'data':{
                        label: item['name'],
                        data: item['themeTableId'],
                        expandedIcon: expandedIcon,
                        collapsedIcon: collapsedIcon,
                        arrchildid:item['arrchildid'],
                        arrparentid:item['arrparentid'],
                        checkStatus:item['checkStatus'],
                        createBy:item['createBy'],
                        child:item['child'],
                        name : item['name'],
                        labelName : item['labelName'],
                        labelId : item['labelId'],
                        createTime : item['createTime'],
                        status : item['status'],
                        themeGroupId:item['themeGroupId'],
                        themeTableId:item['themeTableId'],
                        themeTableCode:item['themeTableCode'],
                        parentid:item['parentid'],
                        description:item['description'],
                    },
                    'leaf': leaf,
                    'themeTableId':item['themeTableId']
                };

                result.push(dataArr);
            }
        }
        return result;
    }

    @Output() isSelectFromTable = new EventEmitter<boolean>();

    // 每一行的表格信息
    outputTabVal(tabval) {
        let tabVal: keywordTableAddtype = {
            parentId: tabval.parentId,
            child:  tabval.child,
            name:  tabval.name,
            status:  tabval.status,
            checkStatus:  tabval.checkStatus,
            create_by : tabval.create_by,
            createTime: tabval.createTime,
            description: tabval.description,
            themeGroupId: tabval.themeGroupId,
            themeTableId: tabval.themeTableId,
            labelId: tabval.labelId,
            labelName: tabval.labelName,
            themeTableCode: tabval.themeTableCode
        };
        this.detailsOutput.emit(tabVal);
    }

    /**
     * 全选
     * @param bool
     * @param tabVal
     */
    _selectAll(bool, tabVal) {
        this.isSelectAll = this.isChose = this.removeTableService.removeAll(bool, tabVal, 'themeTableId');
        this.isSelect = !this.isSelectAll;
        this.isSelectFromTable.emit(this.isSelect);
    }

    /**
     * 单选（多选）
     * @param bool
     * @param scopesId
     * @param length
     */
    _chose(bool, scopesId, length) {
        this.isSelectAll = this.removeTableService.removeChose(bool, scopesId, length)['bool'];
    }

    /**
     * 重置表格复选框、选中的ID
     */
    private _cancelChecked() {
        this.isChose = this.isSelectAll = false;
        this.removeTableService._clearId('scopesId');
    }



    /**
     * 详情（弹窗）
     * @param info
     */
    _details(info: object) {
        this.outputTabVal(info);
        $("#details").modal("show");
    }

    /**
     * 新增子主题词（弹窗）
     * @param info
     */
    _add(info: object) {
        this.outputTabVal(info);
        $("#add").modal("show");
    }

    /**
     * 修改（弹窗）
     * @param info
     */
    _edit(info: object) {
        this.outputTabVal(info);
        $("#edit").modal("show");
    }


    onNodeExpand(event) {
        this.loading = true;
        setTimeout(() => {
            const node = event.node;
            this.queryData.parentId = node.themeTableId;
            this.queryData.pageNo = 1;
            this.queryData.pageSize = 9999;
            this.getChildrenList(this.queryData,node);
            this.loading = false;
        }, 250);

    }
}
